<script setup lang="ts">
import { ref } from 'vue'
import { getConsultOrderPayUrl } from '@/services/consult'
import { error } from '@/utils/tools'
const props = defineProps<{
  // 控制抽屉的显示和隐藏
  show: boolean
  // 订单的实付金额
  actualPayment: number
  // 订单id
  orderId: string
  // 支付成功的回跳地址：问诊订单的地址是http://localhost:3000/room,药品订单不是
  payCallback: string
  // 关闭抽屉前要做的事情
  onClose?: () => void
}>()
const emit = defineEmits<{
  // 父组件改变抽屉显示和隐藏的自定义事件
  (e: 'update:show', show: boolean): void
}>()

// 支付方式
const paymentMethod = ref<0 | 1>()
// 选中支付方式的颜色
const checkedColor = 'var(--cp-primary)'
// 支付成功的回跳地址
// const payCallback = 'http://localhost:3000/room'
// 去支付
const pay = async () => {
  if (paymentMethod.value === undefined) return error('请先选择支付方式')
  const params = {
    paymentMethod: paymentMethod.value,
    orderId: props.orderId,
    payCallback: props.payCallback
  }
  try {
    const { data } = await getConsultOrderPayUrl(params)
    // 正常要跳转到支付地址
    location.href = data.payUrl
  } catch {
    // 支付接口异常：直接跳到支付成功的回跳页面
    location.href = `${props.payCallback}?orderId=${props.orderId}&payResult=true&type=2`
  }
}

</script>

<template>
  <!-- 支付抽屉 -->
  <van-action-sheet :before-close="onClose" :closeable="false" :show="show" @update:show="emit('update:show', $event)"
    title="选择支付方式" :close-on-popstate="false">
    <div class="pay-type">
      <p class="amount">￥{{ actualPayment.toFixed(2) }}</p>
      <van-cell-group>
        <van-cell title="微信支付" @click="paymentMethod = 0">
          <template #icon><cp-icon name="consult-wechat" /></template>
          <template #extra><van-checkbox :checked-color="checkedColor" :checked="paymentMethod === 0" /></template>
        </van-cell>
        <van-cell title="支付宝支付" @click="paymentMethod = 1">
          <template #icon><cp-icon name="consult-alipay" /></template>
          <template #extra><van-checkbox :checked-color="checkedColor" :checked="paymentMethod === 1" /></template>
        </van-cell>
      </van-cell-group>
      <div class="btn">
        <van-button type="primary" round block @click="pay">立即支付</van-button>
      </div>
    </div>
  </van-action-sheet>
</template>

<style lang="scss" scoped>
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }

  .btn {
    padding: 15px;


    .van-button {
      background-color: var(--cp-primary);
      border-color: var(--cp-primary);
    }

  }

  .van-cell {
    align-items: center;

    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }

    .van-checkbox {
      :deep(.van-checkbox__icon) {
        font-size: 16px;
      }

      /* 
        :deep() {
          // 选中的复选框的图片
          .van-checkbox__icon--checked {
            .van-icon {
              background-color: #f00;
              border-color: #f00;
            }
          }
        } */
    }
  }
}
</style>
